# encoding: utf-8
# @File  : monitor.py
# @Author: shaoyun
# @Date  :  2025/05/11
from typing import Dict, List, Any, Union
from bson import ObjectId

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.api.dependencies import get_current_user, admin_required, get_db
from app.db.mongo_manager import MongoDB
from app.models.user import User
from app.services.ai_optimizer import ai_optimizer
from app.services.monitor import Monitor

router = APIRouter()


def convert_objectid_to_str(data: Union[Dict, List, Any]) -> Union[Dict, List, Any]:
    """递归转换所有 ObjectId 为字符串"""
    if isinstance(data, dict):
        return {
            key: convert_objectid_to_str(value)
            for key, value in data.items()
        }
    elif isinstance(data, list):
        return [convert_objectid_to_str(item) for item in data]
    elif isinstance(data, ObjectId):
        return str(data)
    else:
        return data


@router.get("/metrics", response_model=Dict[str, Any])
async def get_system_metrics(
        time_range: str = Query("hour", description="时间范围：hour, day, week"),
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user)
):
    """获取系统指标摘要"""
    metrics = await Monitor.get_system_metrics(db, time_range)
    return convert_objectid_to_str(metrics)


@router.get("/alerts", response_model=List[Dict[str, Any]])
async def get_alerts(
        limit: int = 20,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user)
):
    """获取系统告警信息"""
    alerts = await MongoDB.find_many("alerts", {}, limit=limit)
    # 转换所有 ObjectId 为字符串
    return convert_objectid_to_str(list(alerts))


@router.post("/check-alerts", response_model=List[Dict[str, Any]])
async def check_alerts(
        db: Session = Depends(get_db),
        current_user: User = Depends(admin_required)  # 只有管理员可以手动检查告警
):
    """手动检查告警条件"""
    alerts = await Monitor.check_alerts(db)
    # 转换所有 ObjectId 为字符串
    return convert_objectid_to_str(alerts)


@router.get("/insights", response_model=Dict[str, Any])
async def get_performance_insights(
        time_range: str = Query("day", description="时间范围：hour, day, week"),
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user)
):
    """获取AI生成的性能洞察"""
    insights = await ai_optimizer.generate_performance_insights(time_range)
    return convert_objectid_to_str(insights)


@router.get("/dashboard", response_model=Dict[str, Any])
async def get_dashboard_data(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user)
):
    """获取仪表盘所需的综合数据"""
    # 获取系统指标
    metrics = await Monitor.get_system_metrics(db, "day")

    # 获取最近告警
    alerts = await MongoDB.find_many("alerts", {}, limit=5)

    # 获取节点状态
    nodes = await MongoDB.find_many("nodes", {}, limit=10)

    # 获取最近任务
    recent_tasks = await MongoDB.find_many(
        "tasks",
        {},
        limit=10
    )

    # 获取AI洞察
    insights = await ai_optimizer.generate_performance_insights("day")

    # 构建响应数据
    response_data = {
        "metrics": metrics,
        "alerts": list(alerts),
        "nodes": list(nodes),
        "recent_tasks": list(recent_tasks),
        "insights": insights
    }

    # 递归转换所有 ObjectId 为字符串
    return convert_objectid_to_str(response_data)